package com.wn.procurement.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wn.common.PageBean;
import com.wn.entity.InventoryBookkeeping;
import com.wn.entity.Procurement;
import com.wn.procurement.mapper.ProcurementMapper;
import com.wn.procurement.service.ProcurementService;
import com.wn.procurement.vo.ProcurementVo;
import com.wn.utils.PageBeanUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ProcurementServiceImpl implements ProcurementService {

    @Autowired
    private ProcurementMapper procurementMapper;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public void insert(Procurement procurement) {
        //procurementMapper.insert(procurement);
        rabbitTemplate.convertAndSend("exchangeprocurement", "procurement", procurement);
    }

    @Override
    public void update(Procurement procurement) {
        procurementMapper.update(procurement);
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.delete("procurement");
    }

//    @Override
//    public PageBean<Procurement> getAll() {
//        return null;
//    }

    @Override
    public PageBean<Procurement> getByCondition(ProcurementVo procurementVo) {
        Page<Procurement> page = PageHelper.startPage(procurementVo.getCurrPage(), procurementVo.getPageSize());
        HashOperations hash = redisTemplate.opsForHash();
        //优先查询redis缓存中是否有信息，有直接返回redis中的缓存信息
        if (hash.hasKey("procurement", procurementVo.toString())) {
            List<Procurement> list =(List<Procurement>) hash.get("procurement", procurementVo.toString());
            return PageBeanUtil.getPageBean(list, page, procurementVo.getCurrPage(), procurementVo.getPageSize());
        }
        List<Procurement> list = procurementMapper.getByCondition(procurementVo.getProcurement());
        //把此次查询内容放入redis 过期时间设置为5分钟
        hash.putIfAbsent("procurement", procurementVo.toString(), list);
        redisTemplate.expire("procurement",5, TimeUnit.MINUTES);
        return PageBeanUtil.getPageBean(list, page, procurementVo.getCurrPage(), procurementVo.getPageSize());
    }



}

